<template>
  <div class="details">
    <!--
            修改用户名和密码
            1：定义api
            2:导入api
            3:表单验证
            4：验证通过后调用api修改
            5：修改成功提示一下

       -->
    <el-card>
      <el-tabs>
        <el-tab-pane label="登陆帐户设置">
          <el-form
            ref="form"
            label-width="100px"
            class="details-form"
            :model="form"
            :rules="rules"
          >
            <el-form-item label="姓名" prop="username">
              <el-input v-model="form.username" />
            </el-form-item>
            <el-form-item label="密码" prop="password">
              <el-input v-model="form.password" show-password />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="submit">更新</el-button>
              <el-button>取消</el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        <el-tab-pane label="个人详情" lazy>
          <Info :user-info="initUserinfo" @updateInfo="updateInfo" />
        </el-tab-pane>
        <el-tab-pane label="岗位信息" lazy>
          <Job />
        </el-tab-pane>
      </el-tabs>
    </el-card>
  </div>
</template>
<script>
import { sysUser, sysUserPut } from '@/api/user'
// sysUserPut要求传入所有用户信息
// import Info from './components/Info.vue'
export default {
  components: {
    Info: () => import('./components/Info.vue'),
    Job: () => import('./components/Job.vue')
  },
  data() {
    return {
      id: this.$route.params.id,
      userinfo: '',
      initUserinfo: '',
      form: {
        username: '',
        password: ''
      },
      rules: {
        username: [{ required: true, message: '必填', trigger: 'change' }],
        password: [{ required: true, message: '必填', trigger: 'change' }]
      }
    }
  },
  created() {
    this.getData()
  },
  methods: {
    async getData() {
      const res = await sysUser(this.id)
      this.userinfo = res.data
      // 深拷贝一份数据 传递给info组件
      this.initUserinfo = JSON.parse(JSON.stringify(res.data))
      this.form.username = res.data.username
      // console.log('员工用户信息', res)
    },
    // 更新点击
    submit() {
      this.$refs.form.validate(async(result) => {
        if (result) {
          // 合并对象  {...a,...b}
          // 返回值（合并后的对象）=Object.assign(目标对象,a,b....)
          await sysUserPut(Object.assign({}, this.userinfo, this.form))
          // 更新Info组件内的用户信息
          this.initUserinfo.username = this.form.username
          this.initUserinfo.password = this.form.password
          this.$message.success('修改成功')
        }
      })
    },
    updateInfo(obj) {
      // 更新什么？
      // 1：fome内的username更新  2：当前的userinfo与子组件的用户信息要同步
      this.form.username = obj.username
      this.userinfo = JSON.parse(JSON.stringify(obj))
    }
  }
}
</script>
<style lang="scss" scoped>
.details {
  padding: 20px;
}
.details-form {
  width: 500px;
  margin: 0 auto;
}
</style>
